package cn.amebius.simpledocker.websocket;

import cn.amebius.simpledocker.config.DockerFactory;
import cn.amebius.simpledocker.entity.model.DockerClientModel;
import cn.amebius.simpledocker.websocket.callback.ConAttachCallback;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.model.Frame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

/**
 * @author 阿伟
 * @date 2023/9/26 14:30
 */
@Component
public class ConAttachSocket extends TextAbstractWebsocket{

    private static DockerFactory dockerFactory;

    @Autowired
    public void setFactory(DockerFactory dockerFactory){
        ConAttachSocket.dockerFactory = dockerFactory;
        this.initSocket("AttachSocket");
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        try {
            super.afterConnectionEstablished(session);
            ConAttachCallback<Frame> cac = new ConAttachCallback<>("AttachCallback",session);
            Integer key = (Integer) session.getAttributes().get("key");
            String containerId = (String) session.getAttributes().get("containerId");
            DockerClientModel dcm = dockerFactory.getByKey(key);
            DockerClient dc = dcm.getDockerClient();
            dc.attachContainerCmd(containerId)
                    .withFollowStream(true)
                    .withStdErr(true)
                    .withStdIn(this.getInput(session.getId()))
                    .withLogs(true)
                    .exec(cac);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
